package com.test.service.Impl;

import com.test.Aspect.BusinessException;
import com.test.dao.CanteenMapper;
import com.test.domain.Canteen;
import com.test.domain.CanteenExample;
import com.test.enums.Page;
import com.test.enums.Replay;
import com.test.enums.ReplayCode;
import com.test.service.CanteenService;
import com.test.utils.ReplayUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * CanteenServiceImpl
 *
 * @author HY
 * 2021/05/24 8:42
 **/


@Service
public class CanteenServiceImpl implements CanteenService {

    @Resource
    private CanteenMapper canteenMapper;

    @Override
    public Replay insert(Canteen canteen) {

        if (canteen.getName() == null || canteen.equals("")){
            throw new BusinessException(ReplayCode.REQUIREDNULL_ERR);
        }

        int rs = canteenMapper.insert(canteen);

        if (rs < 1 ){
            throw new BusinessException(ReplayCode.DO_ERR);
        }
        return ReplayUtil.success();
    }

    @Override
    public Replay del(int id) {
        // TODO 删除待完成
        return ReplayUtil.success();
    }

    @Override
    public Replay update(Canteen canteen) {

        if (canteen.getCanteenid() == null || canteen.getCanteenid().equals("")){
            throw new BusinessException(ReplayCode.REQUIREDNULL_ERR);
        }

        CanteenExample canteenExample = new CanteenExample();
        CanteenExample.Criteria criteria = canteenExample.createCriteria();

        criteria.andCanteenidEqualTo(canteen.getCanteenid());

        int rs = canteenMapper.updateByExampleSelective(canteen, canteenExample);

        if (rs < 1 ){
            throw new BusinessException(ReplayCode.DO_ERR);
        }

        return ReplayUtil.success();
    }

    @Override
    public Replay select(Canteen canteen, Page page) {

        if (page.isNull()){
            //抛出空值异常
            throw new BusinessException(ReplayCode.Page_NULL);
        }

        CanteenExample canteenExample = new CanteenExample();
        CanteenExample.Criteria criteria = canteenExample.createCriteria();
        //查询条件添加
        if (canteen.getName().equals("") || canteen.getName() != null) {
            criteria.andNameLike("%"+canteen.getName()+"%");
        }
        canteenExample.setPage(page.getPage());
        canteenExample.setLimit(page.getLimit());

        List<Canteen> canteens = canteenMapper.selectByExample(canteenExample);
        int count = (int) canteenMapper.countByExample(canteenExample);

        return ReplayUtil.success("查询成功", canteens, count);
    }
}
